﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QualitySupervision.Core
{
    public class PaginatedList<T>
    {
        /// <summary>
        /// 当前页
        /// </summary>
        public int pagenum { get; set; }

        //总页面数
        public int TotalPages { get; set; }

        /// <summary>
        /// 总记录数
        /// </summary>
        public int Total { get; set; }

        /// <summary>
        /// 判断是否有上一页
        /// </summary>
        public bool HasPreViousPage => (pagenum > 1);

        /// <summary>
        /// 判断是否有下一页
        /// </summary>
        public bool HasNextPage => pagenum < TotalPages;

        /// <summary>
        /// 分页数据项
        /// </summary>
        public List<T> Items { get; }
        public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
        {
            pagenum = pageIndex;

            Total = count;

            TotalPages = (int)Math.Ceiling(count / (decimal)pageSize);

            Items = items;
        }

        /// <summary>
        /// 创建分页
        /// </summary>
        /// <param name="source">实体信息</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">当前页数据条数</param>
        /// <returns></returns>
        public static async Task<PaginatedList<T>> CreatePagingAsync(IQueryable<T> source, int pageIndex, int pageSize)
        {
            //返回实体总条数
            var count = await source.CountAsync();
            //返回满足条件的分页数据
            var users = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            var pageResultList = new PaginatedList<T>(users, count, pageIndex, pageSize);
            return pageResultList;
        }
    }
}
